using System;
using System.Collections.Generic;
using GalaSoft.MvvmLight.Messaging;
using FeedReaderApp.DataModel;
using FeedReaderApp.Model;
using Windows.ApplicationModel.DataTransfer;

namespace FeedReaderApp.ViewModel
{
    public class ItemDetailViewModel : DataSourceAwareViewModel
    {
        private string _uniqueIdForDeferredLoading;

        public void InitializeFromFeedItemUniqueId(string uniqueId)
        {
            InitializeDataSource();

            if (IsLoading)
            {
                _uniqueIdForDeferredLoading = uniqueId;
            }
            else
            {
                _uniqueIdForDeferredLoading = "";
                LoadByUniqueId(uniqueId);
            }
        }

        private void LoadByUniqueId(string uniqueId)
        {
            var itemToDisplay = FeedsDataSource.Instance.GetItemByUniqueId(uniqueId);

            if (null != itemToDisplay)
            {
                FeedName = itemToDisplay.FeedName;
                Items = FeedsDataSource.Instance.GetItemsByFeedName(FeedName);
            }

            SelectedItem = itemToDisplay;
        }

        protected override void OnLoadingCompleted()
        {
            if (!String.IsNullOrWhiteSpace(_uniqueIdForDeferredLoading))
                LoadByUniqueId(_uniqueIdForDeferredLoading);
        }

        public const string FeedNamePropertyName = "FeedName";
        private string _feedName;
        public string FeedName
        {
            get { return _feedName; }
            set
            {
                Set(FeedNamePropertyName, ref _feedName, value);
            }
        }

        public const string SelectedItemPropertyName = "SelectedItem";
        private FeedItem _selectedFeedItem;
        public FeedItem SelectedItem
        {
            get { return _selectedFeedItem; }
            set 
            {
                Set(SelectedItemPropertyName, ref _selectedFeedItem, value);
            }
        }
        
        public const string ItemsPropertyName = "Items";
        private List<FeedItem> _items; 
        public List<FeedItem> Items
        {
            get { return _items; }
            set
            {
                Set(ItemsPropertyName, ref _items, value);
            }
        }
        public bool Share(DataRequestedEventArgs e)
        {
            if (null == SelectedItem)
            {
                return false;
            }
            else
            {
                DataRequest request = e.Request;
                request.Data.Properties.Title = SelectedItem.Title;
                request.Data.SetText(SelectedItem.Title + " ," + SelectedItem.ContentReWrapped);
                var url = SelectedItem.Uri;
                request.Data.SetUri(new Uri(url));
                return true;
            }
           
        }
    }
}
